package cn.wildfire.chat.kit.group.manage;

import android.annotation.SuppressLint;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.MaterialDialog;
import com.sourcemuch.im.caiba.R;import com.sourcemuch.im.caiba.R2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.wildfire.chat.app.extendsion.classes.VIPSetRequest;
import cn.wildfire.chat.app.extendsion.ui.SmoothToggleAndSlideAnimationForUI;
import cn.wildfire.chat.app.extendsion.ui.ToastTip;
import cn.wildfire.chat.app.extendsion.utils.TextUtils;
import cn.wildfire.chat.kit.contact.model.UIUserInfo;
import cn.wildfire.chat.kit.group.BasePickGroupMemberActivity;
import cn.wildfire.chat.kit.group.GroupViewModel;

public class AddGroupManagerActivity extends BasePickGroupMemberActivity {

    private MenuItem menuItem;
    private List<UIUserInfo> checkedGroupMembers;

    /**
     * 是否来自于VIP设置
     */
    private boolean fromVipSet;

    @Override
    protected void afterViews() {
        try {
            String value = getIntent().getStringExtra("GroupVIP");
            if (value == null || value.length() == 0) {
                fromVipSet = false;
            } else {
                fromVipSet = value.equals("VIPSET");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.afterViews();
    }

    @Override
    protected void onGroupMemberChecked(List<UIUserInfo> checkedUserInfos) {
        this.checkedGroupMembers = checkedUserInfos;
        if (checkedUserInfos == null || checkedUserInfos.isEmpty()) {
            menuItem.setTitle("确定");
            menuItem.setEnabled(false);
        } else {
            menuItem.setTitle("确定(" + checkedUserInfos.size() + ")");
            menuItem.setEnabled(true);
        }
    }

    @Override
    protected int menu() {
        return R.menu.group_manage_add_manager;
    }

    @Override
    protected void afterMenus(Menu menu) {
        menuItem = menu.findItem(R2.id.confirm);
        menuItem.setEnabled(false);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R2.id.confirm) {
            setGroupManager();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setGroupManager() {
        try {
            GroupViewModel groupViewModel = ViewModelProviders.of(this).get(GroupViewModel.class);
            List<String> memberIds = new ArrayList<>(checkedGroupMembers.size());
            for (UIUserInfo info : checkedGroupMembers) {
                memberIds.add(info.getUserInfo().uid);
            }
            String content = fromVipSet ? "设置中..." : "添加中...";
            MaterialDialog dialog = new MaterialDialog.Builder(this)
                    .content(content)
                    .progress(true, 100)
                    .cancelable(false)
                    .build();
            dialog.show();
            if (!fromVipSet) {

                /**
                 * modify by HEKE , 2019/9/9 20:53 TODO 管理员设置时，进行过滤
                 */
                if (!TextUtils.isTextEmpty(ownerId)) {
                    // 取消管理员列表
                    List<String> cancleManagerList = new ArrayList<>();
                    for (int i = 0; i < initCheckedMemberIds.size(); i++) {
                        String value = initCheckedMemberIds.get(i);
                        if (!memberIds.contains(value)) {
                            cancleManagerList.add(value);
                        }
                    }
                    // 新增管理员列表
                    List<String> validAddMemberIds = new ArrayList<>();
                    for (int i = 0; i < memberIds.size(); i++) {
                        String value = memberIds.get(i);
                        if (!initCheckedMemberIds.contains(value)) {
                            validAddMemberIds.add(value);
                        }
                    }
                    // 执行操作
                    if (cancleManagerList != null && cancleManagerList.size() > 0) {
                        groupViewModel.setGroupManager(groupInfo.target, false, cancleManagerList, Collections.singletonList(0), null)
                                .observe(this, booleanOperateResult -> {
                                    dialog.dismiss();
                                    if (booleanOperateResult.isSuccess()) {
                                        finish();
                                    } else {
                                        ToastTip.tip("取消管理员错误 " + booleanOperateResult.getErrorCode());
                                    }
                                });
                    }
                    if (validAddMemberIds != null && validAddMemberIds.size() > 0) {
                        groupViewModel.setGroupManager(groupInfo.target, true, validAddMemberIds, Collections.singletonList(0), null)
                                .observe(this, booleanOperateResult -> {
                                    dialog.dismiss();
                                    if (booleanOperateResult.isSuccess()) {
                                        finish();
                                    } else {
                                        ToastTip.tip("设置管理员错误 " + booleanOperateResult.getErrorCode());
                                    }
                                });
                    }
                } else {
                    groupViewModel.setGroupManager(groupInfo.target, true, memberIds, Collections.singletonList(0), null)
                            .observe(this, booleanOperateResult -> {
                                dialog.dismiss();
                                if (booleanOperateResult.isSuccess()) {
                                    finish();
                                } else {
                                    Toast.makeText(this, "设置管理员错误 " + booleanOperateResult.getErrorCode(), Toast.LENGTH_SHORT).show();
                                }
                            });
                }
            } else {
                /**
                 * modify by HEKE , 2019/8/25 18:14
                 * TODO  制定用户增加VIP权限
                 */
                ArrayList<String> vipUidList = new ArrayList<>();
                for (String member : memberIds) {
                    vipUidList.add(member);
                }
                new VIPSetRequest(AddGroupManagerActivity.this, groupInfo, vipUidList, 20, new VIPSetRequest.OnVipSetResultListener() {
                    @Override
                    public void result(String ret, boolean success) {
                        dialog.dismiss();
                        if (success) {
                            finish();
                        } else {
                            Toast.makeText(AddGroupManagerActivity.this, "设置VIP错误 " + ret, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * modify by HEKE , 2019/9/4 18:55 TODO 测试滑动隐藏或显示搜索栏 HEKE_SEARCHLAYOUT_ADDMANAGER
     */
    protected SmoothToggleAndSlideAnimationForUI smoothToggleAndSlideAnimationForUI;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            if (smoothToggleAndSlideAnimationForUI == null) {
                smoothToggleAndSlideAnimationForUI = new SmoothToggleAndSlideAnimationForUI(this,
                        SmoothToggleAndSlideAnimationForUI.FLAG_GROUP_ADD_REMOVE_MANMAGER);
                smoothToggleAndSlideAnimationForUI.setToggleView(pickGroupMemberFragment.getSearchLayout());
                smoothToggleAndSlideAnimationForUI.setSlideView(pickGroupMemberFragment.getUsersRecyclerView(), 0);
            }
            smoothToggleAndSlideAnimationForUI.onTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.dispatchTouchEvent(ev);
    }

    @SuppressLint("ResourceType")
    @Override
    protected void setTitleCenterThenSetSearchView() {
        super.setTitleCenterThenSetSearchView();
        setToolbarOrReplaceType(true, 3);
        setReplaceTitle(null, R.string.add_group_manager_title);
        setSearchLayoutVisibility(false);
        getRightTxtView().setBackgroundResource(R.drawable.commom_green_radiusmuch);
        getRightTxtView().setTextColor(getResources().getColor(R.color.white));
        setTextThenBinClickForRightTextView(View.VISIBLE, getString(R.string.confirm), new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = getRightTxtView().getText().toString();
                if (text.equals(getString(R.string.confirm))) {
                    setGroupManager();
                } else {
                    // 隐藏搜索内容
                    pickGroupMemberFragment.hideSearchContactFragment();
                }
            }
        });
        pickGroupMemberFragment.setOnPickUserStatusChangeListener(onPickUserStatusChangeListener);
    }

    /**
     * 控制右上角文字变化，搜索显示与取消状态监听
     */
    private OnPickUserStatusChangeListener onPickUserStatusChangeListener = new OnPickUserStatusChangeListener() {
        @Override
        public void showSearchResult(boolean searching) {
            getRightTxtView().setText(searching ? getString(R.string.done_title) : getString(R.string.confirm));
        }
    };

}
